package cn.tedu.order.tcc;

import cn.tedu.order.entity.Order;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @ClassName OrderTccActionImpl
 * @Description:类描述
 * @Author Tedu
 * @Date 2021/7/2 14:07
 * @Version V1.0
 **/
@Component
public class OrderTccActionImpl implements OrderTccAction{
    @Autowired
    private OrderMapper orderMapper;
    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long orderId, Long userId, Long productId, Integer count, BigDecimal money) {
        //插入状态是0的订单,表示是一个冻结的订单
        orderMapper.create(new Order(orderId,userId,productId,count,money,0));
        //第一阶段成功,保存一个一阶段的成功标记
        ResultHolder.setResult(OrderTccAction.class, ctx.getXid(), "p");

        return true;
    }
    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        //如果没有标记,二阶段不执行
        //第一阶段没有成功或者第二阶段已执行过,标记已删除,不再重复执行
        if (ResultHolder.getResult(OrderTccAction.class, ctx.getXid())==null){
            return true;
        }
        //从上下文对象取出orderId
        Long orderId = Long.valueOf(ctx.getActionContext("orderId").toString());

        //订单状态改成1,表示正常状态
        orderMapper.updateStatus(orderId,1);
        //第二阶段成功-提交成功,删除标记
        ResultHolder.removeResult(OrderTccAction.class, ctx.getXid());
        return true;
    }
    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        if (ResultHolder.getResult(OrderTccAction.class, ctx.getXid())==null){
            return true;
        }
        //从上下文对象取出orderId
        Long orderId = Long.valueOf(ctx.getActionContext("orderId").toString());
        orderMapper.deleteById(orderId);
        ResultHolder.removeResult(OrderTccAction.class, ctx.getXid());
        return true;
    }
}
